<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <ul>
        <li><router-link to="/home">Home</router-link></li>
        <li><router-link to="/profile/password">password</router-link></li>
      </ul>
      <router-view></router-view>
    </div>
    <script src="vue.js"></script>
    <script src="vue-router.js"></script>
    <script>
      const Home = {
        template: `<div>Home</div>`,
      };
      const Login = {
        template: `<div>Login</div>`,
      };
      const Profile = {
        template: `
        <div>
          <p>Profile</p>
          <router-view></router-view>
        </div>`,
      };
      const Password = {
        template: `<div>Password</div>`,
      };
      const routes = [
        { 
          name: "home", 
          path: "/home", 
          component: Home 
        },
        { 
          name: "login", 
          path: "/login", 
          component: Login 
        },
        { 
          name: "profile", 
          path: "/profile", 
          component: Profile,
          meta: { requireAuth: true },
          children:[
            {
              name:'password',
              path: "password", 
              component:Password,
             
            }
          ]  
        }
      ];
      var router = new VueRouter({
        routes,
      });
      router.beforeEach((to,from,next)=>{
        //验证你当前访问的路由需要不需要登录，如果需要登录而现在没有登录则跳到登录页
        //如果需要登录你登录了则直接访问
        //如果不需要登录，直接访问
        //一个路由匹配到的所有路由记录会暴露为 $route  的 $route.matched 数组
        const {matched} = to;
        //遍历所有的路由记录，看看是否有某一条路由记录上有requireAuth的meta元素
        let requireAuth = matched.some(record=>record?.meta?.requireAuth);
        if(requireAuth){
          if(localStorage.getItem('login')){
            next();
          }else{
            next('/login');
          }
        }else{
          //如果不需要登录则直接跳转
          next();
        }
      });
      var vm = new Vue({
        el: "#app",
        router,
      });
    </script>
  </body>
</html>
